import Vue from 'vue'
import Router from 'vue-router'
import users from "@/api/users/users";

Vue.use(Router)

const router = new Router({
    mode: 'history',
    routes: [
        {
            path: '/',
            name: 'Index',
            component: resolve => require.ensure([], () => resolve(require('@/views/IndexView')), 'Index'),
            //component:()=>import("@/views/WelcomeView"),
            /*
            meta: {
                keepAlive: true // 需要被缓存
            }*/
        },
        {
            path: '/login',
            name: 'Login',
            component: resolve => require.ensure([], () => resolve(require('@/views/LoginView')), 'LoginView'),
            //component:()=>import("@/views/WelcomeView"),
        },
        {
            path: '/users/center',
            name: 'UsersCenterView',
            component: resolve => require.ensure([], () => resolve(require('@/views/UsersCenterView')), 'UsersCenterView'),
            //component:()=>import("@/views/WelcomeView"),
            meta: {
                requireAuth: true //说明这个路由必须检查登录权限...
            }
        },
        {
            path: '/case/session',
            name: 'SessionView',
            component: resolve => require.ensure([], () => resolve(require('@/views/SessionView')), 'SessionView'),
            //component:()=>import("@/views/WelcomeView"),
        },
        {
            path: '/case/other',
            name: 'AnotherView',
            component: resolve => require.ensure([], () => resolve(require('@/views/AnotherView')), 'AnotherView'),
            //component:()=>import("@/views/WelcomeView"),
        }

    ]
})

//添加路由守卫

router.beforeEach((to, from, next) => {
    if (to.matched.some(record => record.meta.requireAuth)) {
        // 判断该路由是否需要登录权限
        //console.log('该路由需要检查登录权限....')
        //发送一个异步请求;
        users.isLogin().then(resp => {
            if (resp.data.code === 200) {
                next(); //放行.....
            } else {
                next({
                    path: '/login',
                    query: {redirect: to.fullPath} // 将跳转的路由path作为参数，登录成功后跳转到该路由
                })
            }
        })
    } else {
        next();
    }
})

export default router;